package com.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Smile
 */
public class DataUtil {

    /**
     * 将关系对象转换成结构化对象
     *
     * @param dataSource   数据源
     * @param foreignFiled 外键字段
     * @param majorFiled   主键字段
     * @param foreignValue 外键值
     * @param fileds       对应属性
     * @return
     */
    public static List<Map<String, Object>> StructuredObject(List<Map<String, Object>> dataSource, String foreignFiled, String majorFiled, String foreignValue, Map<String, String> fileds) {
        List<Map<String, Object>> unitTreeList = new ArrayList<>();

        Map<String, Object> unit = dataSource.stream().filter((Map<String, Object> s) -> s.get(majorFiled).equals(foreignValue)).findFirst().orElse(null);
        if (unit == null) {
            return unitTreeList;
        }
        unit = getMap(unit, fileds);

        List<Map<String, Object>> units = dataSource.stream().filter((Map<String, Object> s) -> s.get(foreignFiled) != null && s.get(foreignFiled).equals(foreignValue)).collect(Collectors.toList());

        List<Map<String, Object>> children = new ArrayList<>();
        for (Map<String, Object> item : units) {
            String major = item.get(majorFiled).toString();
            children.addAll(StructuredObject(dataSource, foreignFiled, majorFiled, major, fileds));
        }

        if (children.size() > 0) {
            unit.put("children", children);
        }
        unitTreeList.add(unit);
        return unitTreeList;
    }

    private static Map<String, Object> getMap(Map<String, Object> data, Map<String, String> field) {
        Map<String, Object> res = new HashMap<>();
        for (Map.Entry<String, String> item : field.entrySet()) {
            if (!data.containsKey(item.getKey())) {
                continue;
            }
            res.put(item.getValue(), data.get(item.getKey()));
        }
        return res;
    }
}
